package com.hsy.servlet;

import com.hsy.pojo.User;
import com.hsy.service.UserService;
import com.hsy.service.impl.UserServiceImpl;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/userListServlet")
public class UserListServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        Integer startIndex = Integer.valueOf(request.getParameter("startIndex"));
        Integer targetTotal = Integer.valueOf(request.getParameter("targetTotal"));
        Integer pageSize = targetTotal;  // 每页显示的条目数

        // 获取所有用户信息
        List<User> userList = userService.selectUserList(startIndex, targetTotal);

        // 获取总用户数
        Integer totalCount = userService.getTotalUserCount();  // 返回数据库中的用户总数
        Integer totalPages = (int) Math.ceil(totalCount / (double) pageSize);

        // 将用户列表、总页数和当前页码等信息存储在请求域中
        request.setAttribute("userList", userList);
        request.setAttribute("totalCount", totalCount);
        request.setAttribute("totalPages", totalPages);
        request.setAttribute("targetTotal", targetTotal);
        request.setAttribute("currentPage", (startIndex / targetTotal) + 1);  // 当前页码，假设startIndex从0开始

        // 转发到首页
        RequestDispatcher dispatcher = request.getRequestDispatcher(request.getContextPath() + "/static/views/home.jsp");
        dispatcher.forward(request, response);
    }
}

